<?php
namespace app\common;
// 商品供应链接口请求类
// 接口文档：https://www.yuque.com/llsiah/dvtri9/bxwmgmqwhwr703fo
class SchlSdk{
    /** 当前版本号 */
    private $version='2.0';
    private $appid='335482-eEt1E00IHKNNyBqw';
    private $secret='spC9i8ysG1qH78jV5Y5UqfRZP279CE1n';
    /** 环境标识 mock：测试  prod：正式*/
    private $mode='prod';
    /** 测试环境域名 */
    private $mockDomain='https://schl-api-test.szbaoly.com/';
    /** 正式环境域名 */
    private $prodDomain='https://schl-api.szbaoly.com/';
    /** api接口路径 */
    private $queryGoodsCategory='open/xdxt/api/v2/goods/listGoodsCategory';
    private $queryGoodsList='open/xdxt/api/v2/goods/listGoods';
    private $queryGoodsChangeEvent='open/xdxt/api/v2/goods/listGoodsChangeEvent';
    private $queryOrderList='open/xdxt/api/v2/order/listOrderInfo';
    private $orderFreightPreview='open/xdxt/api/v2/order/orderFreightPreview';
    private $createOrder='open/xdxt/api/v2/order/createOrder';
    private $queryExpTrack='open/xdxt/api/v2/order/queryExpTrack';
    private $queryOrderChangeEvent='open/xdxt/api/v2/order/listOrderChangeEvent';

    public function queryGoodsCategory(){
        return $this->requestApi($this->queryGoodsCategory);
    }

    public function queryGoodsList($params){
        return $this->requestApi($this->queryGoodsList, $params);
    }

    public function queryGoodsChangeEvent(){
        return $this->requestApi($this->queryGoodsChangeEvent);
    }

    public function queryOrderList($params){
        return $this->requestApi($this->queryOrderList, $params);
    }

    public function orderFreightPreview($params){
        return $this->requestApi($this->orderFreightPreview,$params);
    }

    public function createOrder($params){
        return $this->requestApi($this->createOrder,$params);
    }

    public function queryExpTrack($params){
        return $this->requestApi($this->queryExpTrack,$params);
    }

    public function queryOrderChangeEvent(){
        return $this->requestApi($this->queryOrderChangeEvent);
    }

    private function requestApi(string $url, $params = array()){
        if (is_null($this->appid) || $this->appid === '' || is_null($this->secret) || $this->secret === '') {
            throw new RuntimeException('配置错误');
        }
        if (is_null($this->mode) || $this->mode === '' || $this->mode === 'mock') {
            $url = $this->mockDomain.$url;
        } else if ($this->mode === 'prod') {
            $url = $this->prodDomain.$url;
        } else {
            throw new RuntimeException('环境标识错误');
        }
        $urlParam = 'appid='.$this->appid.'&nonce='.self::nonce(16).'&timestamp='.time();
        $signature = strtoupper(hash_hmac('sha256',$urlParam.'&key='.$this->secret,$this->secret));
        $url .= '?'.$urlParam.'&signature='.$signature;
        return $this->curl_post($url, $params);
    }

    private static function nonce(int $size = 32): string{
        return implode('', array_map(static function(string $c): string {
            return '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[ord($c) % 62];
        }, str_split(random_bytes($size))));
    }

    private function curl_post(string $url, array $params) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($params),
            CURLOPT_HTTPHEADER => [
                'content-type: application/json'
            ],
        ]);
        $result = curl_exec($ch);
        $err = curl_errno($ch);
        curl_close($ch);
        if ($err) {
            throw new RuntimeException('RequestApi Error：'.$err);
        }
        return $result;
    }
}